import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';

import s from './ButtonGroup.module.css';

export default function ButtonGroup({ className, children, value, onChange }) {
	const [active, setActive] = React.useState(value);
	const [prevValue, setPrevValue] = React.useState();
	React.useMemo(() => {
		if (value !== prevValue) {
			setPrevValue(active);
		}
		if (value !== active && value !== prevValue) {
			setActive(value);
		}
	}, [value]);

	return (
		<div className={cn(className, s.buttonGroup)}>
			{React.Children.map(children, el =>
				React.cloneElement(el, {
					...el.props,
					className: cn(s.item, el.props.className, {
						[s.active]: el.key === active,
					}),
					onClick: e => {
						if (el.props.disabled) return;
						setActive(el.key);
						onChange(el.key);
						if (el.props.onClick) el.props.onClick(e);
					},
				})
			)}
		</div>
	);
}

ButtonGroup.propTypes = {
	className: PropTypes.string,
	children: PropTypes.element,
	value: PropTypes.string,
	onChange: PropTypes.func,
};

ButtonGroup.defaultProps = {
	className: s.buttonGroup,
	onChange: x => x,
};
